<?php

use think\Env;
if(!function_exists('createImg')) {
    function createImg($sourcePath, $targetWidth, $targetHeight)
    {

        if (Env::get('img.baseurl') != "https://" . $_SERVER["HTTP_HOST"] && Env::get('img.baseurl') != "http://" . $_SERVER["HTTP_HOST"]) {
            $sourcePath = str_replace($_SERVER["DOCUMENT_ROOT"], '', $sourcePath);
            $sourcePath = Env::get('img.baseurl') . str_replace("//", '/', $sourcePath);
            $sourcePath = preg_replace("/\.(jpg|jpeg|png|gif|jpeg)$/Uisx", "_" . $targetWidth . "_" . $targetHeight . ".$1", $sourcePath);
            return $sourcePath;
        } elseif (preg_match("/{$targetWidth}_{$targetHeight}/", $sourcePath)) {
            return $sourcePath;
        }
        // 生成新文件名
        $pathInfo = pathinfo($sourcePath);
        $extension = isset($pathInfo['extension']) ? strtolower($pathInfo['extension']) : 'jpg';
        $filename = isset($pathInfo['filename']) ? $pathInfo['filename'] : 'image';
        $dirname = isset($pathInfo['dirname']) ? $pathInfo['dirname'] : '';

        $newFileName = $filename . "_{$targetWidth}_{$targetHeight}." . $extension;
        $targetPath = $dirname . '/' . $newFileName;
        if (file_exists($targetPath)) {
            return path2url($targetPath);
        }

        // 检查源路径是否有效
        if (empty($sourcePath) || !is_string($sourcePath)) {
            return '';
        }


        // 检查文件是否已存在
        if (file_exists($targetPath)) {
            //return path2url($targetPath); // 如果文件已存在，直接返回路径
        }

        // 确保 GD 库已安装
        if (!extension_loaded('gd')) {
            throw new Exception('GD 库未安装');
        }

        // 获取原图信息
        list($originalWidth, $originalHeight, $sourceType) = @getimagesize($sourcePath);

        if (!$originalWidth || !$originalHeight) {
            return $sourcePath; // 无法获取图片信息，返回原路径
        }

        // 根据文件类型创建图像资源
        switch ($sourceType) {
            case IMAGETYPE_JPEG:
                $sourceImage = imagecreatefromjpeg($sourcePath);
                $extension = 'jpg';
                break;
            case IMAGETYPE_PNG:
                $sourceImage = imagecreatefrompng($sourcePath);
                $extension = 'png';
                break;
            case IMAGETYPE_GIF:
                $sourceImage = imagecreatefromgif($sourcePath);
                $extension = 'gif';
                break;
            default:
                return $sourcePath; // 不支持的图像类型，直接返回原路径
        }

        if (!$sourceImage) {
            return $sourcePath;
        }

        // 如果原图尺寸已经符合要求，不需要处理
        if ($originalWidth == $targetWidth && $originalHeight == $targetHeight) {
            imagedestroy($sourceImage);
            copy($sourcePath, $targetPath);
            return path2url($sourcePath);
        }

        // 创建目标图片资源
        $targetImage = imagecreatetruecolor($targetWidth, $targetHeight);

        // 保持PNG和GIF的透明度
        if ($sourceType == IMAGETYPE_PNG || $sourceType == IMAGETYPE_GIF) {
            imagealphablending($targetImage, false);
            imagesavealpha($targetImage, true);
            $transparent = imagecolorallocatealpha($targetImage, 255, 255, 255, 127);
            imagefilledrectangle($targetImage, 0, 0, $targetWidth, $targetHeight, $transparent);
        }

        // 计算原图和目标图的宽高比
        $originalRatio = $originalWidth / $originalHeight;
        $targetRatio = $targetWidth / $targetHeight;

        // 计算缩放比例
        $scaleX = $targetWidth / $originalWidth;
        $scaleY = $targetHeight / $originalHeight;

        // 使用较大的缩放比例，确保完全填充目标尺寸
        $scale = max($scaleX, $scaleY);

        $newWidth = intval($originalWidth * $scale);
        $newHeight = intval($originalHeight * $scale);

        // 创建临时缩放图片
        $tempImage = imagecreatetruecolor($newWidth, $newHeight);

        // 保持透明度
        if ($sourceType == IMAGETYPE_PNG || $sourceType == IMAGETYPE_GIF) {
            imagealphablending($tempImage, false);
            imagesavealpha($tempImage, true);
            $transparent = imagecolorallocatealpha($tempImage, 255, 255, 255, 127);
            imagefilledrectangle($tempImage, 0, 0, $newWidth, $newHeight, $transparent);
        }

        // 先将原图缩放到临时图片
        imagecopyresampled(
            $tempImage,
            $sourceImage,
            0,
            0,
            0,
            0,
            $newWidth,
            $newHeight,
            $originalWidth,
            $originalHeight
        );

        // 计算裁剪位置
        if ($originalRatio > $targetRatio) {
            // 宽图片：宽度填满，高度从底部裁剪
            $cropX = 0;  // 宽度不裁剪
            $cropY = max(0, $newHeight - $targetHeight);  // 高度从底部裁剪，保留上半部分
        } else {
            // 高图片：从上下和左右的中间裁剪，保留真正中间的部分
            $cropX = intval(($newWidth - $targetWidth) / 2);   // 宽度居中裁剪
            $cropY = intval(($newHeight - $targetHeight) / 2); // 高度居中裁剪
        }

        // 从临时图片裁剪到目标图片
        imagecopyresampled(
            $targetImage,
            $tempImage,
            0,
            0,
            $cropX,
            $cropY,
            $targetWidth,
            $targetHeight,
            $targetWidth,
            $targetHeight
        );

        // 释放临时图片内存
        imagedestroy($tempImage);

        // 保存图像
        switch ($extension) {
            case 'jpg':
                imagejpeg($targetImage, $targetPath, 90);
                break;
            case 'png':
                imagepng($targetImage, $targetPath, 9);
                break;
            case 'gif':
                imagegif($targetImage, $targetPath);
                break;
        }

        // 释放资源
        imagedestroy($sourceImage);
        imagedestroy($targetImage);

        return path2url($targetPath);
    }
}


if (!function_exists('path2url')) {
    function path2url($path)
    {
        $path = preg_replace('/^public/', '/public', $path);
        $path = str_replace('\\', '/', $path);
        $path = str_replace(str_replace('\\', '/', ROOT_PATH), '', $path);
        $path = str_replace('//', '/', $path);
        $path = preg_replace('/^public/', '', $path);
        $path = Env::get('img.baseurl') . $path;
        return $path;
    }
}


    /**
     * 获取图片
     * @param string|null $src 图片路径
     * @param int $w 宽度
     * @param int $h 高度
     * @return string
     */
if(!function_exists('getImg')) {
    function getImg(?string $src, int $w, int $h): string
    {
        // 1. 基础校验：路径为空或非字符串，返回空字符串（可根据需求调整默认图）
        if (!is_string($src) || trim($src) === '') {
            return '';
        }
        $path = ROOT_PATH . 'public' . DS . 'uploads' . DS . uniqid() . '.jpg';
        if (substr($src, 0, 4) == "http" && !strstr($src, Env::get('img.baseurl')) && !strstr($src, "yangjc.com") && !strstr($src, "gxyushengwenhua.com")) {
            $context = stream_context_create([
                "http" => [
                    "method" => "GET",
                    "header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\r\n",
                    "timeout" => 30
                ],
                "ssl" => [
                    "verify_peer" => false,
                    "verify_peer_name" => false,
                    "allow_self_signed" => true
                ]
            ]);
            $img = file_get_contents($src, false, $context);

            if ($img) {
                file_put_contents($path, $img);
                $src = $path;
            }
        }

        $src = str_replace('\\', '/', trim($src));
        $src = str_replace($_SERVER['DOCUMENT_ROOT'], '', $src);
        $imgBaseUrl = Env::get('img.baseurl'); // 图片基础域名（需确保Env类可正常调用）
        $sizeMarker = "_{$w}_{$h}"; // 尺寸标记（如"_750_422"）

        // 2. 处理逻辑：复用原规则，适配动态宽高参数
        // 条件：路径以"/"开头 + 非HTTP链接 + 未包含目标尺寸标记
        if (substr($src, 0, 1) === "/"
            && substr($src, 0, 4) !== "http"
            && !preg_match("/{$sizeMarker}/", $src)
        ) {
            // 拼接服务器绝对路径，调用图片生成方法
            $absolutePath = $_SERVER["DOCUMENT_ROOT"] . $src;
            $url = createImg($absolutePath, (string)$w, (string)$h);
            @unlink($path);
            return $url;
        } else {
            // 直接拼接基础域名返回（若已带HTTP则原路径返回，否则补基础域名）
            return substr($src, 0, 4) === "http" ? $src : $imgBaseUrl . $src;
        }
    }
}
